package com.xt.base.model.base;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.xt.base.dao.hibernate.code.IAutoCreateCode;
import com.xt.base.exception.SystemError;
import com.xt.base.pojo.BasePOJO;

/**
 * 二进制数据模型 <br>
 * <br>
 * 
 * <p>
 * <a href="BlobDATA.java.html"><i>查看源文件</i></a>
 * </p>
 * 
 * @author 杨洪波
 * @version $Revision: $<br>
 *          $Id: $
 * @hibernate.class table="BlobDATA" dynamic-update="true" dynamic-insert="true" batch-size="200" 
 */
public class BlobDATA extends BasePOJO implements IAutoCreateCode{
	private static final long serialVersionUID = -1189941046555255148L;
	
	/** 用于存储二进制数据，比如附件、或者word格式的页面闻到那股数据
	 * 此表必须与主表分离，以减轻主表的负载 */
	private byte[] content;
	
	private String title;

	/**
	 * @hibernate.property column="Content" lazy="true" type="com.xt.base.dao.hibernate.userType.BinaryBlobType"
	 * @return
	 */
	public byte[] getContent() {
		return content;
	}

	public void setContent(byte[] content) {
		this.content = content;
	}
	
	/**
	 * @hibernate.property column="Title"
	 */
	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}
	
	public BlobDATA(){	}
	
	public BlobDATA(File file,String title){
		this.title = title;
		int len = (int)file.length();
		byte[] bytes = new byte[len];
		InputStream is = null;
		try{
			is = new FileInputStream(file);
			is.read(bytes);
		}catch(Exception e){
			e.printStackTrace();
			throw new SystemError(this,new Object[]{file},"在BlobDATA.BlobDATA(File file)中出错",e);
		}finally{
				try { 
					if(is!=null) is.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw new SystemError(this,new Object[]{file},"在BlobDATA.BlobDATA(File file)的finally中出错",e);
				}
		}
		content = bytes;
	}
	
	public BlobDATA(InputStream is,int length){
		byte[] bytes = new byte[length];
		try {
			is.read(bytes);
		} catch (IOException e) {
			e.printStackTrace();
			throw new SystemError(this,new Object[]{is,length},"在BlobDATA.BlobDATA(InputStream is,int length)中出错",e);
		}
		content = bytes;
	}
	
	public BlobDATA(byte[] bytes){
		content = bytes;
	}
	
	public static BlobDATA file2BlobDATA(File file,String title){
		return new BlobDATA(file,title);
	}
	
	public OutputStream getOutputStream(){
		OutputStream os = null;
		os = new ByteArrayOutputStream(getBytes().length); 
		try {
			os.write(getBytes());
		} catch (IOException e) {
			e.printStackTrace();
			throw new SystemError(this,new Object[]{null},"在BlobDATA.getOutputStream()中出错",e);
		}
		return os;
	}
	
	public byte[] getBytes(){
		return (byte[])this.content;
	}
	
}
